#include "RobotItemDialog.h"
#include "ui_RobotItemDialog.h"
#include <QDebug>
#include <QColorDialog>

RobotItemDialog::RobotItemDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::RobotItemDialog)
{
    ui->setupUi(this);
    //设置标题
    this->setWindowTitle("创建Map中的机器人及Monitor");
    //建立值链接
    connect(ui->spinBoxID, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this, [&](int value){
        m_baseData.num = value;
    });
    connect(ui->spinBoxX, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this, [&](int value){
        m_baseData.x = value;
    });
    connect(ui->spinBoxY, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this, [&](int value){
        m_baseData.y = value;
    });
    connect(ui->lineEditIP, &QLineEdit::textChanged, this, [&](const QString& text){
        m_netData.ip = text;
    });
    //初始化
    ui->spinBoxID->setValue( RobotItem::getItemCount() );
    ui->spinBoxX->setValue(0);
    ui->spinBoxY->setValue(0);
    ui->lineEditIP->setText("192.168.0.0");
    //为itemView添加scene
    QGraphicsScene* scene = new QGraphicsScene(QRectF(-50, -50, 100, 100), ui->itemView);
    ui->itemView->setScene(scene);
    //添加预览item
    RobotItem* item = new RobotItem(QRectF(0, 0, 0, 0), m_baseData);
    scene->addItem(item);
    //按钮改变颜色
    ui->btnColor->setStyleSheet("background-color:" + item->getColor().name() + ";");
    connect(ui->btnColor, &QPushButton::clicked, this, [&](){
        QColor color = QColorDialog::getColor(item->getColor(), this, "选择颜色");
        if (color.isValid()) {
            //有闪退bug
//            item->setColor(color);
            ui->btnColor->setStyleSheet("background-color:" + color.name() + ";");
        }
    });
}

RobotItemDialog::~RobotItemDialog()
{
    for (QGraphicsItem* item : ui->itemView->scene()->items() ) {
        delete item;
    }
    delete ui->itemView->scene();
    delete ui;
}
